import moment from 'moment';
import { Time } from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/components/LeaveDatePicker/LeaveDatePicker';
import cloneDeep from 'lodash/cloneDeep';

export const TIME_TYPE_EN = {
    上午: 'am',
    下午: 'pm'
};

export const TIME_TYPE_CN = {
    am: '上午',
    pm: '下午'
};

// 处理回填的加班数据
export function formatFillBackOvertimeData(item, formValueMap) {
    item.forEach(v => {
        let o = formValueMap[v.formId];
        const {
            formId,
            options: { disabled }
        } = v;

        const { overTimeType, overTimeTypeName, duration, durationText, startTime, endTime } = formValueMap;

        if (formId === 'overTimeType') {
            o = {
                key: overTimeType,
                label: overTimeTypeName
            };
        }

        if (formId === 'duration') {
            o = {
                duration,
                durationText
            };
        }

        if (formId === 'startTime' || formId === 'endTime') {
            o = {
                time: moment(formId === 'startTime' ? startTime : endTime),
                unit: 3,
                country: 'zh',
                type: formId,
                disabled
            };
        }

        v.initialValue = o;
    });

    return item;
}

// 处理请假回填数据
export function formatFillBackLeaveData(item, formValueMap) {
    item.forEach(subItem => {
        const {
            formId,
            options: { disabled }
        } = subItem;
        let o = formValueMap[subItem.formId];

        const {
            startTime,
            endTime,
            leaveType,
            leaveTypeName,
            formatTime,
            endTimeType,
            startTimeType,
            duration,
            durationText
        } = formValueMap;

        if (formId === 'duration') {
            o = {
                duration,
                durationText
            };
        }

        if (formId === 'leaveType') {
            o = {
                key: leaveType,
                label: leaveTypeName
            };
        }

        if (formId === 'startTime' || formId === 'endTime') {
            const time = moment(formId === 'startTime' ? startTime : endTime);
            let timeValue;
            const dType = formId === 'startTime' ? TIME_TYPE_EN[startTimeType] : TIME_TYPE_EN[endTimeType];

            if (formatTime === 3) {
                timeValue = moment(formId === 'startTime' ? startTime : endTime).format('HH:mm');
            }

            o = {
                time,
                timeValue,
                unit: formatTime,
                country: 'zh',
                dayType: dType,
                type: formId,
                disabled
            };
        }

        subItem.initialValue = o;
    });

    return item;
}

// 处理出差回填
export function formatFillBackBusinessTripData(item, formValueMap) {
    item.forEach(subItem => {
        const {
            formId,
            options: { disabled }
        } = subItem;
        let o = formValueMap[subItem.formId];

        const { startTime, endTime, formatTime, endTimeType, startTimeType, duration, durationText } = formValueMap;

        if (formId === 'duration') {
            o = {
                duration,
                durationText
            };
        }

        if (formId === 'startTime' || formId === 'endTime') {
            const time = moment(formId === 'startTime' ? startTime : endTime);
            let timeValue;
            const dType = formId === 'startTime' ? TIME_TYPE_EN[startTimeType] : TIME_TYPE_EN[endTimeType];

            if (formatTime === 3) {
                timeValue = moment(formId === 'startTime' ? startTime : endTime).format('HH:mm');
            }

            o = {
                time,
                timeValue,
                unit: formatTime,
                country: 'zh',
                dayType: dType,
                type: formId,
                disabled
            };
        }

        subItem.initialValue = o;
    });

    return item;
}

// 处理销假回填
export function formatFillBackVacationCancelData(item, formValueMap) {
    item.forEach(subItem => {
        const { formId } = subItem;
        let o = formValueMap[subItem.formId];

        const {
            startTime,
            endTime,
            duration,
            durationText,
            applicationLeaveNo,
            leaveTypeName,
            leaveType,
            leaveLong
        } = formValueMap;

        if (formId === 'duration') {
            o = {
                duration,
                durationText
            };
        }

        if (formId === 'startTime' || formId === 'endTime') {
            o = moment(formId === 'startTime' ? startTime : endTime);
        }

        if (formId === 'vacationSelect') {
            o = {
                applicationLeaveNo,
                leaveTypeName,
                leaveType,
                leaveLong
            };
        }

        subItem.initialValue = o;
    });
    return item;
}

// 处理回填数据
export function formDataFormat(val) {
    const { formValueMap, formList } = cloneDeep(val);
    // // 把表单值写入到表单list中
    if (formList && Array.isArray(formList)) {
        const newData = formList.map(item => {
            // 套件赋值
            item.employeeCode = formValueMap.employeeCode;
            if (item.cmpType === 'custom') {
                // 请假套件赋值
                if (item.tag === 'Leave') {
                    // 请假
                    item.children = formatFillBackLeaveData(item.children, formValueMap);
                } else if (item.tag === 'Overtime') {
                    // 加班
                    item.children = formatFillBackOvertimeData(item.children, formValueMap);
                } else if (item.tag === 'BusinessTrip') {
                    item.children = formatFillBackBusinessTripData(item.children, formValueMap);
                } else if (item.tag === 'LeaveCancel') {
                    item.children = formatFillBackVacationCancelData(item.children, formValueMap);
                } else if (item.tag === 'PostApply') {
                    item.postApplyId = formValueMap.id;
                    // 职位申请原因，暂时这么处理
                    item.reason = formValueMap.reason;
                } else {
                    item.employeeCode = formValueMap?.employeeCode;
                    item.children.forEach(subItem => {
                        if (Object.keys(formValueMap).length > 0) {
                            subItem.initialValue = formValueMap[subItem.formId];
                            if (subItem.tag === 'Date') {
                                subItem.initialValue = formValueMap[subItem.formId]
                                    ? moment(formValueMap[subItem.formId])
                                    : moment();
                            }
                        }
                    });
                }
            } else if (Object.keys(formValueMap).length > 0) {
                item.initialValue = formValueMap[item.formId];
                if (item.dataType) {
                    item.initialValue = formValueMap[item.formId] ? moment(formValueMap[item.formId]) : moment();
                }
            }
            return item;
        });
        return newData;
    }
    return [];
}

const getTime = ({ date, dayType, type, country, unit }) => {
    if (!date) return null;
    const tempdayType = dayType || (type === 'startTime' || type === 'returnToWork' ? 'am' : 'pm');
    if (unit === 1) {
        return date.format(`YYYY-MM-DD ${Time[country][tempdayType][type]}:00`);
    }
    if (unit === 2) {
        return date.format(`YYYY-MM-DD ${Time[country][tempdayType][type]}:00`);
    }
    if (!unit) {
        return date.format('YYYY-MM-DD');
    }
    return date.format('YYYY-MM-DD HH:mm:00');
};

const concatTime = ({ time, timeValue }) => `${time.format('YYYY-MM-DD')} ${timeValue}:00`;

// 请假/出差时间数据组装
export function formatLeaveFormDate(values) {
    const valueKeys = Object.keys(values);
    if (
        valueKeys.length === 0 ||
        !(valueKeys.includes('leaveType') || valueKeys.includes('businessTripTotalExpense'))
    ) {
        return values;
    }
    let o = {};
    const { duration, startTime, endTime } = values;
    const formatTime = startTime.unit;
    let timeType = {};
    let st = getTime({ ...startTime, date: startTime.time });
    let et = getTime({ ...endTime, date: endTime.time });

    // 半天
    if (formatTime === 2) {
        timeType = {
            startTimeType: TIME_TYPE_CN[startTime.dayType],
            endTimeType: TIME_TYPE_CN[endTime.dayType]
        };
    }

    if (formatTime === 3) {
        st = concatTime({ ...startTime });
        et = concatTime({ ...endTime });
    }

    o = {
        ...values,
        ...timeType,
        ...duration,
        formatTime,
        startTimeType: TIME_TYPE_CN[startTime.dayType],
        endTime: et,
        startTime: st,
        endTimeType: TIME_TYPE_CN[endTime.dayType]
    };

    if (valueKeys.includes('leaveType')) {
        const {
            leaveType: { key, label }
        } = values;
        o = { ...o, leaveType: key, leaveTypeName: label };
    }

    return o;
}

// 处理提交给服务端的加班数据
export function formatOvertimeFormData(values) {
    const valueKeys = Object.keys(values);
    if (valueKeys.length === 0 || !valueKeys.includes('overTimeType')) {
        return values;
    }
    const { overTimeType, startTime, endTime, duration } = values;

    const o = {
        ...values,
        overTimeTypeName: overTimeType.label,
        overTimeType: overTimeType.key,
        startTime: startTime.time.format('YYYY-MM-DD HH:mm:ss'),
        endTime: endTime.time.format('YYYY-MM-DD HH:mm:ss'),
        ...duration
    };
    return o;
}

// 处理交给服务端的销假数据
export function formatVacationCancelFormData(values) {
    const { vacationSelect = {}, duration, startTime, endTime } = values || {};
    const obj = {
        ...values,
        ...duration,
        ...vacationSelect,
        vacationSelect: vacationSelect?.applicationLeaveNo,
        startTime: moment.isMoment(startTime) ? startTime.format('YYYY-MM-DD HH:mm:ss') : startTime,
        endTime: moment.isMoment(endTime) ? endTime.format('YYYY-MM-DD HH:mm:ss') : endTime
    };
    return obj;
}

// 处理交给服务端的制度数据
export function formatInstitutionFormData(values) {
    const { scope = [] } = values || {};
    const keyarr = [];
    const labelarr = [];
    scope.forEach(item => {
        keyarr.push(item.value);
        labelarr.push(item.label);
    });

    const obj = {
        ...values,
        scope: {
            key: keyarr?.length > 0 ? `${keyarr.join(',')},` : '', // 根据需求key后面要加逗号，为啥不用value？因为之前前端给的就是key...
            label: labelarr?.length > 0 ? labelarr.join(',') : '' // 根据后端需求。label不要后面不加逗号
        }
    };
    return obj;
}

export const getSummary = map => {
    const summaryArr = [];
    Object.keys(map).forEach(key => {
        summaryArr.push(`${[key]}: ${map[key]}`);
    });
    return summaryArr.join('<br />');
};
